/**
 * Created by WLG on 2018/11/12.
 */
const mongoose = require('mongoose');
const redisDB = require('../lib/redisManage');
let ServerConfig = require('../config/serverConfig');
let SystemConst = require('../config/systemConst');
let Chat = mongoose.model('Chat');
let ChatMsg = mongoose.model('ChatMsg');
/**
 * ChatMsg 服务
 */
class ChatMsgService{
    static async load(item){
        return await ChatMsg.find(item).exec();
    }
    static async save(item){
        let tempItem = new ChatMsg(item);
        return await tempItem.save()
    }

    static async getLastChatMsgCache(chatID,refresh){
        let result = "{}";
        let key = this.createLastChatMsgKey(chatID);
        let item = null;
        if(refresh){

        }else{
            item = await redisDB.get(key);
        }
        if(item){
            result = item;
        }else {
            result = await ChatMsg.find({chatID:chatID})
                .sort({serverReceiveTime:-1}).limit(1)
                .exec();
            if (result) {
                await this.setLastChatMsgCache(chatID,result);
            }
        }
        if(result instanceof Array){
            result = result[0];
        }
        return result;
    }
    static async setLastChatMsgCache(chatID,item){
        let key = this.createLastChatMsgKey(chatID);
        await redisDB.set(key,item,ServerConfig.socketCommonCacheTime)
    }
    static createLastChatMsgKey(id){
       return "LastChatMsg:"+id;
    }
    static async searchChatMsgList(chatID,lastSortID){
        let result = null;
        if(lastSortID){
            result = await ChatMsg.find(
                    {
                        chatID:chatID,
                        _id:{$lt : lastSortID},
                    })
                .sort({serverReceiveTime:-1}).limit(ServerConfig.chatMsgPageBaseSize)
                .exec();
        }else{
            result = await ChatMsg.find(
                    {
                        chatID:chatID
                    })
                .sort({_id:-1}).limit(ServerConfig.chatMsgPageBaseSize)
                .exec();
        }
        return result;
    }

    static async searchImageFile(chatID){
        let result = await ChatMsg.find({
                chatID:chatID,
                chatMsgType:{$in:[SystemConst.ChatMsgType.Image,SystemConst.ChatMsgType.File]}
            })
            .sort({serverReceiveTime:-1})
            .exec();
        return result;
    }

    static async delMsg(chatMsgID){
        let id = mongoose.Types.ObjectId(chatMsgID);
        return await ChatMsg.deleteOne({_id:id});
    }

}

module.exports = ChatMsgService;